<?php  
import ('miho.db.exception.*');
/**
 * Class that represents connection to database.
 * Basicaly, this is abstraction layer for PDO.
 *
 * @package miho.db
 * @author miho
 */
class Connection{
  
  protected $_pdo;
  public function getPDO(){
    return $this->_pdo;
  }
      
  protected $_tablePreffix = 'yacms_';
  public function getTablePreffix(){
    return $this->_tablePreffix;
  }
  
  private function __construct($pdo){
    $this->_pdo = $pdo;
  }  
  
  
  public function query($sql){
    $pdo = $this->_pdo;
    $stmt = $pdo->prepare($sql);
    
    $pdo->beginTransaction();
    $stmt->execute();
    
    if($stmt->errorCode()!='00000'){
      $error = $stmt->errorInfo();
      $pdo->rollback();
      throw new Exception($error[2]);
    }
    $pdo->commit();
    return $stmt;
  }
  
  
  /**
   * Connection factory
   *
   * @param string $uri 
   * @return Connection
   * @author miho
   */
  public static function makeConnection($uri){
    $conf = parse_url($uri);
    
    try{
      $pdo = new PDO(
        $conf['scheme'].
        ':host='.$conf['host'].
        ';dbname='.substr($conf['path'],1),
        $conf['user'],
        $conf['pass']
      );
      
      self::$_activeConnection = new Connection($pdo);
      return self::$_activeConnection;
      
    }catch(Exception $e){
      throw new ConnectionException($e->getMessage());
    }
  }
  
  protected static $_activeConnection;
  public static function getActiveConnection(){
    return self::$_activeConnection;
  }
  
}

?>